from flask import Flask
from app.models import db
from app.controllers import blueprints

def create_app(config=None):
    """创建Flask应用"""
    app = Flask(__name__)
    
    # 配置应用
    app.config.from_mapping(
        SECRET_KEY='dev',
        SQLALCHEMY_DATABASE_URI='sqlite:///app.db',
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        JSON_AS_ASCII=False,  # 允许JSON响应包含非ASCII字符（如中文）
        JSONIFY_MIMETYPE='application/json; charset=utf-8'  # 设置正确的MIME类型和字符集
    )
    
    if config:
        app.config.update(config)
    
    # 初始化数据库
    db.init_app(app)
    
    # 注册蓝图
    for blueprint in blueprints:
        app.register_blueprint(blueprint)
    
    # 注册首页路由
    @app.route('/')
    def index():
        from flask import render_template
        return render_template('index.html')
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    return app